# -*- coding: UTF-8 -*-

import MediaHelper
import gtkImageAppBase
import pygtk
from ImageHelper import CanAutoOrient
# pygtk.require('2.0')
import gtk
import os, sys, datetime

class GtkMediaOrderByDate(gtkImageAppBase.GtkImageAppBase):

    def __init__(self):
        
        # initialize base application
        gtkImageAppBase.GtkImageAppBase.__init__(self)
        
        # initialize folders and lists
        self._dstFolder = ''
        self._convertList = []
        
        # load glade XML
        xml = gtk.glade.XML('gtkMediaOrderByDate.glade', 'scrolledwindow1')
        
        self._resultLabel = xml.get_widget('label3')
        self._destEntry = xml.get_widget('filechooserbutton1')
        self._destEntry.connect('file-set', self._destChanged)
        self._destEntry.connect('selection-changed', self._destChanged)
        self._destNameFormat = xml.get_widget('entry1') 
        self._autoOrient = xml.get_widget('checkbutton1')
        canAutoOrient = MediaHelper.CanAutoOrient()
        self._autoOrient.set_state(canAutoOrient)
        if not canAutoOrient:
            self._autoOrient.set_sensitive(False)
            self._autoOrient.set_tooltip_text("Please install ImageMagick (http://www.imagemagick.org/) and add it to your PATH")
        self._detectSeries = xml.get_widget('checkbutton3')
        self._symLink = xml.get_widget('checkbutton4')
        if os.name != 'posix':
            self._symLink.set_sensitive(False)
            self._symLink.set_active(False)
        else:
            self._symLink.connect("clicked", self._symLinkClicked)
        self._subFolder = xml.get_widget('checkbutton5')
        self._subFolder.connect('clicked', self._subFolderClicked)
        self._subFolderFormat = xml.get_widget('entry3')
        
        # Process button
        self._processBtnText = "Process"
        self._processButton = gtk.Button
        self._processButton = xml.get_widget('button1')
        self._processButton.connect("clicked", self._processClicked)
        self._processButton.set_sensitive(True)

        # Export button
        self._exportBtnText = "Export"
        self._exportButton = gtk.Button
        self._exportButton = xml.get_widget('button2')
        self._exportButton.connect("clicked", self._exportClicked)
        self._exportButton.set_sensitive(False)
        
        # convert table
        self._convertTable = gtk.Table
        self._convertTable = xml.get_widget('table1')
        
        # append to base container
        self._frame = xml.get_widget('scrolledwindow1')
        self._frame.connect('show', self._on_show)
        self.append(xml.get_widget('scrolledwindow1'), gtk.Label("Order-by-Date"))
        
        # initialize internal states
        self._running = False        
 
    def _on_show(self, event):
        srcFiles = self.getFiles()
        if srcFiles.count() > 0:
            # show result
            self._processButton.set_label(self._processBtnText + " %d file(s)" % len(srcFiles))
        else:
            self._processButton.set_label(self._processBtnText)
 
    def _subFolderClicked(self, event):
        if self._subFolder.get_active():
            self._subFolderFormat.set_sensitive(True)
        else:
            self._subFolderFormat.set_sensitive(False)
            
 
    def _symLinkClicked(self, event):
        if self._symLink.get_active():
            self._autoOrient.set_active(False)
            self._autoOrient.set_sensitive(False)
        else:
            if CanAutoOrient():
                self._autoOrient.set_sensitive(True)
        
    def _destChanged(self, event):
        self._dstFolder = self._destEntry.get_filename().decode()
        dstFolder = self._dstFolder
        
        # enable process button if possible
        srcValid = len(self._convertList)
        dstValid = os.path.exists(dstFolder) and self._destNameFormat.get_text() != ''
        if srcValid and dstValid:
            self._exportButton.set_sensitive(True)
            self._exportButton.set_tooltip_text('')
        else:
            self._exportButton.set_sensitive(False)
            if not srcValid:
                self._exportButton.set_tooltip_text('No files to export (start processing first).')
            else:
                self._exportButton.set_tooltip_text("Output folder dosn't exists.")
        pass


    def _processClicked(self, event):
        self._convertList = []
        files = self.getFiles()
        
        if file == None or files.count() == 0:
            self._resultLabel.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color("red"))
            self._resultLabel.set_text('No source file(s) selected, scan for media files first.')
            return
        
        self._clearConvertTable(new_file_count=files.count())
        
        self._resultLabel.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color("black"))
        # check sub folder settings
        if self._subFolder.get_active():
            sub_folder = self._subFolderFormat.get_text()
        else:
            sub_folder = None
        
        # try to sort files
        try:
            convertList = MediaHelper.SortedFileOutput(srcFiles=files.getDateSorted(),
                                                      fileNameFormat=self._destNameFormat.get_text(),
                                                      sub_folder=sub_folder,
                                                      series=self._detectSeries.get_active(),
                                                      onlyFileTime=self.getModeFileDate())
            if convertList:
                self._convertList = convertList
                self._resultLabel.set_text('%s file(s) ready to copy/link' % len(convertList))
                
                
                row = 1
                rootPath = self.getRootFolder()
                for src, dst in convertList:
                    srcLabel = gtk.Label(os.path.relpath(src, rootPath))
                    srcLabel.set_alignment(0, 0.5)
                    dirLabel = gtk.Image()
                    dirLabel.set_from_stock(gtk.STOCK_GO_FORWARD, gtk.ICON_SIZE_SMALL_TOOLBAR)
                    dstLabel = gtk.Label(dst)
                    dstLabel.set_alignment(0, 0.5)
                    self._convertTable.attach(srcLabel, 0, 1, row, row + 1, gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL, xpadding=4, ypadding=4)
                    self._convertTable.attach(dirLabel, 2, 3, row, row + 1, gtk.FILL, gtk.FILL, xpadding=4, ypadding=4)
                    self._convertTable.attach(dstLabel, 4, 5, row, row + 1, gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL, xpadding=4, ypadding=4)
                    srcLabel.show()
                    dirLabel.show()
                    dstLabel.show()
                    row += 1
        except:
            self._resultLabel.set_text("Exception: " + sys.exc_value.message)
            self._resultLabel.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color("red"))
            pass
        
        # update export button
        self._destChanged(event)
        pass


    def _exportClicked(self, event):
        
        self._resultLabel.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color("black"))
        
        def _incr_callback(src, n, dst, successful):
            rel_path = os.path.relpath(src, self.getRootFolder())
            self._resultLabel.set_text('%s / %s exported (%s)' % (n + 1, len(self._convertList), rel_path))
            gtk.main_iteration()
            pass
        
        try:
            nOk, nFailed = MediaHelper.ExecuteConvertList(dest_path=self._dstFolder, conver_list=self._convertList, sym_link=self._symLink.get_active(), auto_orient=self._autoOrient.get_state(), incr_callback=_incr_callback)
            result = '%s file(s) exported, %s failed' % (nOk, nFailed)
        except:
            result = "Exception: " + sys.exc_value.message
            self._resultLabel.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color("red"))
        
        self._resultLabel.set_text(result)
        
        pass


    def run(self):
        gtk.main()
        pass


    
    def _clearConvertTable(self, new_file_count=0):
        n = len(self._convertTable.get_children())
        for c in self._convertTable.get_children():
            if n <= 5: break
            self._convertTable.remove(c)
            n -= 1
        # set to new size
        self._convertTable.resize(new_file_count + 1, 5)



if __name__ == '__main__':
    GtkWin = GtkMediaOrderByDate()
    GtkWin.show()
    pass

